package com.ash.print;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;

public class InTemplatePreview {

    public static void main(String[] args) {
        // 假设的纸张尺寸和分辨率
        int width = (int) Math.round(76 * 2.8346);
        int height = (int) Math.round(130 * 2.8346);

        // 创建一个BufferedImage作为预览画布
        BufferedImage previewImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D对象以在BufferedImage上绘制
        Graphics2D g2d = previewImage.createGraphics();

        // 设置背景色（可选）
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        g2d.setStroke(new BasicStroke(2f)); // 边框宽度为2个单位

        // 绘制边框
        g2d.setColor(Color.black);
        g2d.drawRect(5, 5, width - 20, height-120);

        g2d.drawString("入库标签", 80, 20); // 示例：打印文字
        g2d.drawImage(qrcode(width, height), 10, 30, width - 30, height/6, null);

        g2d.drawString("入库货架号：", 20, 120); // 示例：打印文字
        g2d.drawString("取件号：", 20, 140); // 示例：打印文字
        g2d.drawString("收件人：", 20, 160); // 示例：打印文字
        g2d.drawString("打印时间：", 20, 180); // 示例：打印文字
        g2d.drawString("货物类型：", 20, 200); // 示例：打印文字

        // 关闭Graphics2D对象
        g2d.dispose();

        // 使用JLabel和JFrame显示预览图像
        JLabel label = new JLabel(new ImageIcon(previewImage));
        JFrame frame = new JFrame("Print Preview");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    public static BufferedImage qrcode(int width, int height) {
        String barcodeData = "1234567890";


        try {
            // 创建QRCodeWriter实例
            MultiFormatWriter barcodeWriter = new MultiFormatWriter();

            // 设置编码参数
            HashMap<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            // 生成BitMatrix
            BitMatrix bitMatrix = barcodeWriter.encode(barcodeData, BarcodeFormat.CODE_128, width, height / 6, hints);

            // 将BitMatrix转换为BufferedImage
            BufferedImage bufferedImage = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            return bufferedImage;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
